/**
 * 情节内存 - IntelliMark适配版
 * 简化版本的情节记忆管理
 */

import { Episode, EpisodeFilter, EpisodicMemory as IEpisodicMemory } from "../types/memory";

export class EpisodicMemory implements IEpisodicMemory {
  public type: 'episodic' = 'episodic';
  public namespace: string;
  public enabled: boolean;
  public episodes: Episode[];
  public maxEpisodes: number;

  constructor(namespace: string = 'default', maxEpisodes: number = 1000) {
    this.namespace = namespace;
    this.enabled = true;
    this.episodes = [];
    this.maxEpisodes = maxEpisodes;
  }

  async addEpisode(episode: Episode): Promise<void> {
    this.episodes.push(episode);

    // 按时间排序
    this.episodes.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());

    // 保持数量限制
    if (this.episodes.length > this.maxEpisodes) {
      this.episodes = this.episodes.slice(0, this.maxEpisodes);
    }
  }

  getEpisode(episodeId: string): Episode | undefined {
    return this.episodes.find(ep => ep.id === episodeId);
  }

  getEpisodes(limit?: number, filter?: EpisodeFilter): Episode[] {
    let filtered = [...this.episodes];

    // 应用过滤器
    if (filter) {
      if (filter.dateRange) {
        filtered = filtered.filter(ep =>
          ep.timestamp >= filter.dateRange!.start &&
          ep.timestamp <= filter.dateRange!.end
        );
      }

      if (filter.tags && filter.tags.length > 0) {
        filtered = filtered.filter(ep =>
          filter.tags!.some(tag => ep.tags.includes(tag))
        );
      }

      if (filter.importance) {
        filtered = filtered.filter(ep =>
          ep.importance >= filter.importance!.min &&
          ep.importance <= filter.importance!.max
        );
      }
    }

    return limit ? filtered.slice(0, limit) : filtered;
  }

  searchEpisodes(query: string, limit?: number): Episode[] {
    const queryLower = query.toLowerCase();
    const matched = this.episodes.filter(ep =>
      ep.title.toLowerCase().includes(queryLower) ||
      ep.description.toLowerCase().includes(queryLower) ||
      ep.content.toLowerCase().includes(queryLower) ||
      ep.tags.some(tag => tag.toLowerCase().includes(queryLower))
    );

    return limit ? matched.slice(0, limit) : matched;
  }

  async deleteEpisode(episodeId: string): Promise<void> {
    this.episodes = this.episodes.filter(ep => ep.id !== episodeId);
  }

  async updateEpisode(episodeId: string, episode: Episode): Promise<void> {
    const index = this.episodes.findIndex(ep => ep.id === episodeId);
    if (index !== -1) {
      this.episodes[index] = episode;
      // 重新排序
      this.episodes.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
    }
  }

  async clear(): Promise<void> {
    this.episodes = [];
  }

  async save(): Promise<void> {
    // 简化实现：在内存中保存
  }

  async load(): Promise<void> {
    // 简化实现：从内存中加载
  }
}

export default EpisodicMemory;